﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xenta.Api;
using Xenta.Entities;
using Xenta.Enums;
using Xenta.Security;
using Xenta.Structs;
using Xenta.Utils;

namespace Xenta.Operations
{
    #region __General__

    /// <summary>
    /// Creates a catalog category.
    /// </summary>
    public class CreateCatalogCategory : CreateAuditable<CatalogCategoryEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
            }
        }

        /// <summary>
        /// Gets or sets the parent folder identifier.
        /// </summary>
        public int ParentID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public CatalogCategoryFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Construct(IUnitOfWork uow, CatalogCategoryEntity entity)
        {
            base.Construct(uow, entity);

            entity.Parent = ParentID == 0
                ? null
                : uow.Execute(new GetCatalogCategory
                {
                    ThrowsException = true,
                    EntityID = ParentID
                }).Result;
            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Updates the catalog category.
    /// </summary>
    public class UpdateCatalogCategory : UpdateAuditable<CatalogCategoryEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
            }
        }

        /// <summary>
        /// Gets or sets the parent folder identifier.
        /// </summary>
        public int ParentID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public CatalogCategoryFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Revise(IUnitOfWork uow, CatalogCategoryEntity entity)
        {
            base.Revise(uow, entity);

            entity.Parent = ParentID == 0 ? null : uow.Execute(new GetCatalogCategory
            {
                ThrowsException = true,
                EntityID = ParentID
            }).Result;
            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Updates the catalog category statistics.
    /// </summary>
    public class UpdateCatalogCategoryStats : OperateEntityByID<CatalogCategoryEntity>
    {
        #region Utilities

        protected override void Work(IUnitOfWork uow, out CatalogCategoryEntity result)
        {
            var category = uow.Execute(new GetCatalogCategory
            {
                ThrowsException = true,
                EntityID = EntityID
            }).Result;

            uow.Flush();
            uow.SqlQuery("exec fwk_CatalogCategories_UpdateStats @CategoryID=:CategoryID, @UpdatedOn=:UpdatedOn")
                .SetInt32("CategoryID", category.EntityID)
                .SetDateTime("UpdatedOn", DateTime.UtcNow)
                .ExecuteUpdate();
            uow.Flush();

            result = uow.Execute(new RefreshEntity<CatalogCategoryEntity>
            {
                Entity = category
            }).Result;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the catalog category.
    /// </summary>
    public class DeleteCatalogCategory : DeleteEntity<CatalogCategoryEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
            }
        }

        #endregion

        #region Utilities

        protected override void Destruct(IUnitOfWork uow, CatalogCategoryEntity entity)
        {
            foreach(var i in entity.Childs)
            {
                uow.Execute(new DeleteCatalogCategory
                {
                    EntityID = i.EntityID
                });
            }
            foreach(var i in entity.Translations)
            {
                uow.Execute(new DeleteCatalogCategoryTranslation
                {
                    EntityID = i.EntityID
                });
            }
            foreach(var i in entity.Attributes)
            {
                uow.Execute(new UnmapLookupAttributeFromCatalogCategory
                {
                    EntityID = entity.EntityID,
                    ChildID = i.EntityID
                });
            }
            foreach(var i in entity.Items)
            {
                uow.Execute(new UnmapCatalogCategoryFromCatalogItem
                {
                    EntityID = i.EntityID,
                    ChildID = entity.EntityID
                });
            }
            foreach(var i in entity.Suppliers)
            {
                uow.Execute(new UnmapCatalogCategoryFromCatalogSupplier
                {
                    EntityID = i.EntityID,
                    ChildID = entity.EntityID
                });
            }
            base.Destruct(uow, entity);
        }

        #endregion
    }

    /// <summary>
    /// Gets the catalog category by identifier.
    /// </summary>
    public class GetCatalogCategory : GetEntity<CatalogCategoryEntity>,
        IApiOperation
    {
    }

    #endregion

    #region __Translation__

    /// <summary>
    /// Creates a category translation.
    /// </summary>
    public class CreateCatalogCategoryTranslation : CreateTranslation
        <TCatalogCategoryEntity, CatalogCategoryEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
            }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Construct(IUnitOfWork uow, TCatalogCategoryEntity entity)
        {
            base.Construct(uow, entity);

            entity.Name = StringHelper.EnsureNotNull(Name).TrimToLen(100);
        }

        #endregion
    }

    /// <summary>
    /// Updates the category translation.
    /// </summary>
    public class UpdateCatalogCategoryTranslation : UpdateTranslation
        <TCatalogCategoryEntity, CatalogCategoryEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
            }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Revise(IUnitOfWork uow, TCatalogCategoryEntity entity)
        {
            base.Revise(uow, entity);

            entity.Name = StringHelper.EnsureNotNull(Name).TrimToLen(100);
        }

        #endregion
    }

    /// <summary>
    /// Saves a category translation.
    /// </summary>
    public class SaveCatalogCategoryTranslation : SaveTranslation
        <TCatalogCategoryEntity, CatalogCategoryEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
            }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out TCatalogCategoryEntity result)
        {
            var translation = uow.Execute(new GetCatalogCategoryTranslationByLanguage
            {
                HolderID = HolderID,
                LanguageID = LanguageID
            }).Result;
            if(translation == null)
            {
                translation = uow.Execute(new CreateCatalogCategoryTranslation
                {
                    HolderID = HolderID,
                    LanguageID = LanguageID,
                    Name = Name
                }).Result;
            }
            else
            {
                translation = uow.Execute(new UpdateCatalogCategoryTranslation
                {
                    EntityID = translation.EntityID,
                    LanguageID = LanguageID,
                    Name = Name
                }).Result;
            }
            result = translation;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the category translation.
    /// </summary>
    public class DeleteCatalogCategoryTranslation : DeleteTranlsation
        <TCatalogCategoryEntity, CatalogCategoryEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
            }
        }

        #endregion
    }

    /// <summary>
    /// Gets the category translation.
    /// </summary>
    public class GetCatalogCategoryTranslation : GetTranlsation
        <TCatalogCategoryEntity, CatalogCategoryEntity>,
        IApiOperation
    {
    }

    /// <summary>
    /// Gets the category translation.
    /// </summary>
    public class GetCatalogCategoryTranslationByLanguage : GetTranlsationByLanguage
        <TCatalogCategoryEntity, CatalogCategoryEntity>,
        IApiOperation
    {
    }

    #endregion

    #region __Search__

    /// <summary>
    /// Search over catalog category collection.
    /// </summary>
    public class SearchCatalogCategories : SearchOperation<CatalogCategoryEntity>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public SearchCatalogCategories()
        {
            Term = SearchTerm.Empty;
            SortDir = SortDirection.Ascending;
            SortBy = new []
            {
                CatalogCategorySortBy.ID
            };
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the search term.
        /// </summary>
        public SearchTerm Term
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the language identifier.
        /// </summary>
        public int? LanguageID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the parent category identifier.
        /// </summary>
        public int? ParentID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the supplier identifier.
        /// </summary>
        public int? SupplierID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the supplier identifier.
        /// </summary>
        public int? ItemID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public CatalogCategoryFlags FlagMask
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort direction.
        /// </summary>
        public SortDirection SortDir
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort by.
        /// </summary>
        public CatalogCategorySortBy[] SortBy
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<CatalogCategoryEntity> Build(IUnitOfWork uow, IQueryable<CatalogCategoryEntity> query)
        {
            query = base.Build(uow, query);
            query = query.FilterByFlags(x => (int)x.Flags, (int)FlagMask);
            switch(Term.Mode)
            {
                case SearchTerm.SearchMode.StartsWith:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            i.Name.StartsWith(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Name.StartsWith(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.EndsWith:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            i.Name.EndsWith(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Name.EndsWith(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.Contains:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            i.Name.Contains(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Name.Contains(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.Equals:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                            i.Name.Equals(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Name.Equals(Term.Keyword)));
                    break;
                default:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i => i.Language.EntityID == LanguageID.Value));
                    break;
            }
            if(ParentID.HasValue)
                query = query.Where(x => x.ParentID == ParentID.Value);
            if(SupplierID.HasValue)
                query = query.Where(x => x.Suppliers.Any(i => i.EntityID == SupplierID.Value));
            if(ItemID.HasValue)
                query = query.Where(x => x.Items.Any(i => i.EntityID == ItemID.Value));
            if(SortBy != null)
            {
                for(int i = 0; i < SortBy.Length; i++)
                {
                    switch(SortBy[i])
                    {
                        case CatalogCategorySortBy.SupplierCount:
                            query = query.OrderBy(x => x.SupplierCount, SortDir, i != 0);
                            break;
                        case CatalogCategorySortBy.ItemCount:
                            query = query.OrderBy(x => x.ItemCount, SortDir, i != 0);
                            break;
                        case CatalogCategorySortBy.CreatedOn:
                            query = query.OrderBy(x => x.CreatedOn, SortDir, i != 0);
                            break;
                        default:
                            query = query.OrderBy(x => x.EntityID, SortDir, i != 0);
                            break;
                    }
                }
            }
            return query;
        }

        #endregion
    }

    /// <summary>
    /// Gets the collection of categories as a dictionary, where 
    /// key - category identifier and value - category name.
    /// </summary>
    public class GetCatalogCategoryDictionary : SearchOperation<TCatalogCategoryEntity, Int32, String>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public GetCatalogCategoryDictionary()
        {
            Term = SearchTerm.Empty;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the language identifier.
        /// </summary>
        public int LanguageID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the search term.
        /// </summary>
        public SearchTerm Term
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public CatalogCategoryFlags FlagMask
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<TCatalogCategoryEntity> Build(IUnitOfWork uow, IQueryable<TCatalogCategoryEntity> query)
        {
            query = base.Build(uow, query);
            query = query.FilterByFlags(x => (int)x.Holder.Flags, (int)FlagMask);
            query = query.Where(x => x.Language.EntityID == LanguageID);
            switch(Term.Mode)
            {
                case SearchTerm.SearchMode.StartsWith:
                    query = query.Where(x => x.Name.StartsWith(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.EndsWith:
                    query = query.Where(x => x.Name.EndsWith(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.Contains:
                    query = query.Where(x => x.Name.Contains(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.Equals:
                    query = query.Where(x => x.Name.Equals(Term.Keyword));
                    break;
            }
            query = query.OrderBy(x => x.Name);
            return query;
        }

        protected override IQueryable<KeyValuePair<Int32, String>> Map(IQueryable<TCatalogCategoryEntity> query)
        {
            return query.Select(x => new KeyValuePair<Int32, String>(x.Holder.EntityID, x.Name));
        }

        #endregion
    }

    #endregion

    #region __Map__

    /// <summary>
    /// Maps the lookup attribute to catalog category.
    /// </summary>
    public class MapLookupAttributeToCatalogCategory : MapOperation
        <CatalogCategoryEntity, LookupAttributeEntity>,
        ISecuredOperation, IApiOperation
    {
        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
            }
        }
    }

    /// <summary>
    /// Unmaps the lookup attribute from catalog category.
    /// </summary>
    public class UnmapLookupAttributeFromCatalogCategory : UnmapOperation
        <CatalogCategoryEntity, LookupAttributeEntity>,
        ISecuredOperation, IApiOperation
    {
        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("CTLG");
            }
        }
    }

    #endregion
}
